import fetch from 'common/src/utils/fetch';
import UTILS from "common/src/utils/utils";
import { getAllCollege } from 'common/src/api/user'

/**
 * 最大尝试次数
 * @type {number}
 */
const MAX_ATTEMPT_TIMES = 60;

/**
 * 延迟处理时间，单位ms
 * @type {number}
 */
const DELAY_TIME = 500;

const getFileStatus = (key) => {
  return fetch({
    url: `/api/designservice/common/exportExcelResult/${key}`,
    method: 'get'
  });
};

const doDownload = (path, fileName, url = "") => {
  if (!url) {
    url = `/api/commonservice/obsfile/downloadfile?objectkey=${path}`;
    url=encodeURI(url);
  }
  return fetch({
    url: url,
    method: 'get',
    responseType: "blob",
    timeout: 0
  }).then(res => {
    UTILS.downloadFile(
      res,
      fileName,
      fileName.substr(fileName.lastIndexOf(".") + 1)
    );
  });
};

const downloadFile = (key, fileName, getStatusFunc, currentVue, isEncode = false) => {
  if (!getStatusFunc) {
    getStatusFunc = getFileStatus;
  }
  let times = 0;
  const attemptDownload = () => {
    setTimeout(() => {
      getStatusFunc(key).then(res => {
        times++;
        if (res && res.data && res.data.path) {
          //let path =isEncode?encodeURI(res.data.path):res.data.path;
          //doDownload(path, fileName);
          doDownload(res.data.path, fileName);
          return;
        }
        if (times < MAX_ATTEMPT_TIMES) {
          attemptDownload();
        } else {
          currentVue && currentVue.$eduAlert("导出异常，请联系管理员");
        }
      });
    }, DELAY_TIME);
  };
  attemptDownload();
};

const downloadZip = (key, url, fileName, getStatusFunc, currentVue) => {
  let times = 0;
  const attemptDownload = () => {
    setTimeout(() => {
      getStatusFunc(key).then(res => {
        times++;
        if (res.code === 200 && res.data.status) {
          doDownload(null, fileName, url);
          return;
        }
        if (times < MAX_ATTEMPT_TIMES) {
          attemptDownload();
        } else {
          currentVue && currentVue.$eduAlert("导出异常，请联系管理员");;
        }
      });
    }, DELAY_TIME);
  };
  attemptDownload();
};

const initAllCollege = (colleges) => {
  const result = [];
  getAllCollege(0, 1, 1).then(res => {
    res.data.forEach(item => {
      colleges.push({
        collegeId: item.deptCode,
        collegeIdI18n: item.deptName
      });
    });
    colleges = result;
  });
};

export default {
  downloadFile,
  doDownload,
  downloadZip,
  initAllCollege
};
